import java.util.LinkedList;
import java.util.Queue;

/**
 * 1926. 迷宫中离入口最近的出口
 * https://leetcode.cn/problems/nearest-exit-from-entrance-in-maze/
 */
class Solution {
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};
    int m, n;
    boolean[][] vist;
    public int nearestExit(char[][] maze, int[] entrance) {
        int ret = 0;
        m = maze.length;
        n = maze[0].length;//行，列
        vist = new boolean[m][n];
        Queue<int[]> q = new LinkedList<>();

        q.offer(new int[]{entrance[0], entrance[1]});
        vist[entrance[0]][entrance[1]] = true;

        while(!q.isEmpty()) {
            ret++;
            int sz = q.size();
            for(int i = 0; i < sz; i++) {
                int[] tmp = q.poll();
                int a = tmp[0], b = tmp[1];
                for(int j = 0; j < 4; j++) {
                    int x = a + dx[j], y = b + dy[j];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && maze[x][y] == '.') {
                        //判断是否已经到出口
                        if(x == 0 || x == m - 1 || y == 0 || y == n -1) return ret;

                        q.offer(new int[]{x, y});
                        vist[x][y] = true;
                    }
                }
            }
        }
        //出不去
        return -1;
    }
}